package com.fancy.middleware.common.service.impl;

import com.fancy.middleware.common.service.SessionService;
import io.netty.channel.Channel;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class SessionServiceImpl implements SessionService {

    private Map<Integer, Channel> channelMap = new ConcurrentHashMap<>();

    @Override
    public synchronized void bind(Integer serialNumber, Channel channel) {
        channelMap.put(serialNumber, channel);
    }

    @Override
    public synchronized void unbind(Integer serialNumber) {
        Channel channel = getChannel(serialNumber);
        channel.close();
        channelMap.remove(serialNumber);
    }

    @Override
    public synchronized void unbind(Channel channel) {
        channel.close();
        Collection<Channel> values = channelMap.values();
        values.remove(channel);
    }


    @Override
    public Channel getChannel(Integer serialNumber) {
        return channelMap.get(serialNumber);
    }
}
